﻿namespace Arms.Domain.Modules.Orders
{
    using Arms.Domain.Modules.Products;
    using Arms.Framework.Security.Encryptors;
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class Order : Entity
    {
        public Order()
        {
            this.ProductsInOrders = new HashSet<ProductsInOrder>();
        }

        #region Properties

        public string OrderNumber { get; set; }
        public int OrderHeaderID { get; set; }
        public double SubTotal { get; set; }
        public double Tax { get; set; }
        public double Total { get; set; }
        public OrderState OrderState { get; set; }
        public OrderType OrderType { get; set; }
        public DateTime OrderDate { get; set; }

        #endregion

        #region Navigation

        public virtual OrderHeader OrderHeader { get; set; }
        public virtual ICollection<ProductsInOrder> ProductsInOrders { get; set; }

        #endregion

        #region Members
        /// <summary>
        /// Assigns an order number if it is empty.
        /// Order number format is {Order header number}{Index of this order}
        /// </summary>
        public void CalculateOrderNumber()
        {
            if (string.IsNullOrEmpty(this.OrderNumber))
            {
                //string letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                //int index = this.OrderHeader.Orders.ToList().IndexOf(this);
                //this.OrderNumber = string.Format("{0}{1}", this.OrderHeader.OrderHeaderNumber, letters[index]);
                this.OrderNumber = PasswordGenerator.Generate(8, false, false);
            }
        }
        /// <summary>
        /// Sums the price all products within all orders and assigns that value to SubTotal.
        /// </summary>
        public void CalculateSubTotal()
        {
            this.SubTotal = this.ProductsInOrders.Select(x => x.Product).Sum(y => y.Price);
        }

        #endregion
    }
}
